<?php

/**
 * 安心站长axzz.cn，一个追求技术创造者。让网站、小程序、APP牛起来……
 *
 * cighsen02 3651872575
 *
 * Create at: 2024.05.03
 * Update at: 2025.11.24
 */

namespace Twoir\Service\Info;

use Config;
use Exception;
use Twoir\Service\BaseInfo;
use Twoir\System\Support\ParamTrait;

/**
 * 信息列表
 */
class Lists extends BaseInfo
{
    use ParamTrait;
    // 允许字段
    const ALLOW = ['classid', 'tablename', 'page'];
    // 分页大小
    private int $pageSize = 10;
    // 当前所位置
    private int $currentPage = 0;
    // 默认排序
    private string $orderBy = '';
    // 当次拉取缓存列表
    private $info;
    /**
     * 栏目id或表名
     *
     * @param string|int $classid
     */
    public function __construct(int|string $classid = null)
    {
        global $public_r;
        // 每页数量 默认10
        if ($public_r['qlistinfonum'] > 0) $this->pageSize = $public_r['qlistinfonum'];

        $this->initialize($classid);
    }

    /**
     * 获取列表
     *
     * @param array $add
     * @return array
     *
     * @throws Exception
     */
    public function get(array $add): array
    {
        global $class_r;

        // 过滤无关参数
        $add = $this->paramFilter($add);

        if (empty($add)) throw new Exception("参数错误!", 9200);

        if (!isset($add['classid']) || empty($add['classid'] = (int)$add['classid'])) {

            if (!isset($add['tablename']) || empty($add['tablename'])) {

                throw new Exception("classid或tablename必要参数", 9200);
            }
        }

        // 每页数量
        if (isset($add['classid'], $class_r[$add['classid']]['lencord']) && $class_r[$add['classid']]['lencord'] && $this->pageSize != $class_r[$add['classid']]['lencord']) {

            $this->pageSize = $class_r[$add['classid']]['lencord'];
        }
        // 默认排序
        if (isset($add['classid'], $class_r[$add['classid']]['reorder']) && $class_r[$add['classid']]['reorder']) {

            $this->orderBy = $class_r[$add['classid']]['reorder'];
        }
        // 当前页
        if (isset($add['page']) && $add['page'] > 1) $this->currentPage = $add['page'] - 1;
        // 键名采用小驼峰命名
        $modelName  = camel_case($this->modelName());
        // 定义获取的字段
        $field      = Config::twoir('api.' . $modelName . '.list') ?? ['*'];
        // 条件
        $where      = isset($add['classid']) ? $this->getWhere($add['classid']) : [];

        if (0 < $num = $this->getCount($where)) {

            $result = $this->getList($where, $field, '', $this->orderBy, 0, $this->pageSize, $this->currentPage);

            return [
                // 参数说明：询查条件，获取的字段(不写或*表示全部)，分组，排序规则，拉取数量，分页大小，当前页，获取表类型doc、check和正常表
                'list' 			=> $this->format($result),
                'currentpage'	=> ++$this->currentPage,
                'totalpage' 	=> $num > $this->pageSize ? ceil($num / $this->pageSize) : 1
            ];
        }

        return [];
    }
}
